/**
 * 
 */
package com.iwords.web.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.service.LearningStatusServiceLocal;
import com.iwords.service.SysLibServiceLocal;
import com.iwords.service.UserServiceLocal;
import com.iwords.service.WordServiceLocal;
import com.iwords.utils.CodeUtils;
import com.iwords.utils.HttpUtils;
import com.iwords.constants.Constants;
import com.iwords.enums.KnownLevel;
import com.iwords.utils.StringUtils;
import com.iwords.service.object.LearningStatusEntity;
import com.iwords.service.object.SysLibEntity;
import com.iwords.service.object.SysLibWordsEntity;
import com.iwords.web.base.BaseAction;

/**
 * @author       BOLIN.HBC 
 * @time         2011-4-5    
 * @description  用户学习状态-SERVLET       
 */
@WebServlet(name = "learningAction", urlPatterns = {"/ajaxLearning", "/learningStatus"})
public class LearningAction extends BaseAction<LearningStatusEntity> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @EJB
    SysLibServiceLocal sysLibService;
    @EJB
    private LearningStatusServiceLocal learningStatusService;
    @EJB
    private WordServiceLocal wordService;
    @EJB
    private UserServiceLocal userService;

    public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        if (this.getUserId(req) == null) {
            this.sendRedirect(req, res, Constants.LOGIN_PAGE_JSP, null);
            return;
        }
        
        if(!checkUser(req)){
            this.sendRedirect(req, res,"alipayStart", null);
            return ;
        }
        
        
        String action = req.getParameter("action");
        if (Constants.LEARNINGSTATUS_MOVE_SYSLIB.equals(action)) {

            doMoveSysLib(req, res);

        } else if (Constants.LEARNINGSTATUS_CHANGE_WORDSTATUS.equals(action)) {
            doChangeStatus(req, res);
        } else if (Constants.LEARNINGSTATUS_LIST.equals(action)) {
            doGetStatusList(req, res);
        } else if (Constants.LEARNINGSTATUS_STUDY.equals(action)) {
            doGetAllWordStatusByType(req, res);
        } else if (Constants.LEARNINGSTATUS_NEXT_WORD.equals(action)) {
            doGetNextLevelWord(req, res);
        }
    }

    public void doGetAllWordStatusByType(HttpServletRequest req, HttpServletResponse res) {
        LearningStatusEntity entity = initEntity(req);
        if (entity.getLibid() == null) {
            if (userService.find(this.getUserId(req)).getCurrentlib() == null) {
                this.sendRedirect(req, res, "sysLib?action=list", null);
                return ;
            }
            entity.setLibid(userService.find(this.getUserId(req)).getCurrentlib());
        }

        // 从来没有学习过,则跳到选课本的页面
        if (entity.getLibid() == null) {
            this.sendRedirect(req, res, Constants.CHOOSE_PAGE_JSP, null);
        }
        if (entity.getFamiliarity() == null || entity.getFamiliarity() == 0) {
            entity.setFamiliarity(KnownLevel.Unknown.getValue());
        }
        Integer familiarity = entity.getFamiliarity();

        SysLibWordsEntity currentWord = new SysLibWordsEntity();

        SysLibEntity currentLib = sysLibService.findSysLibById(entity.getLibid());
        currentLib.setDownNum(sysLibService.getStudyLibNum(this.getUserId(req), entity.getLibid(), KnownLevel.Known.getValue()));
        currentLib.setSurplus(currentLib.getQuantity() - currentLib.getDownNum());

        Map<String, Integer> map = learningStatusService.findAllLearningNumber(entity);

        currentWord.setSens(new ArrayList<String>());
        // 获取当前level的第一个单词
        entity.setFamiliarity(familiarity);
        List<LearningStatusEntity> resultList = learningStatusService.getLevelList(entity);
        if (resultList != null && resultList.size() > 0) {
            currentWord = resultList.get(0).getWord();
        }

        initWord(currentWord);

        if (familiarity == null || familiarity == 0) {
            familiarity = 1;
        }
        req.setAttribute("numberMap", map);
        req.setAttribute("currentLib", currentLib);
        req.setAttribute("currentWord", currentWord);
        req.setAttribute("familiarity", familiarity);
        this.forward(req, res, Constants.WORD_JSP);
    }

    public void doGetNextLevelWord(HttpServletRequest req, HttpServletResponse res) throws IOException, JSONException {

        LearningStatusEntity entity = initEntity(req);

        // 0 表示上一个单词,1表示下一个单词
        String udtype = req.getParameter("udtype");
        if (udtype == null || udtype.isEmpty()) {
            udtype = Constants.DOWN_TYPE;
        }
        long wordid = 0;
        if (req.getParameter("wordid") != null) {
            wordid = Long.parseLong(req.getParameter("wordid"));

        } else {
            return;
        }
        SysLibWordsEntity cu = null;

        if (entity.getLibid() == null) {
            entity.setLibid(userService.find(this.getUserId(req)).getCurrentlib());

        }
        Integer f = entity.getFamiliarity();
        if (f == null || f == 0) {
            f = 1;
        }
        List<LearningStatusEntity> resultList = learningStatusService.getLevelList(entity);
        int index = 0;
        if (resultList != null && resultList.size() > 0) {
            for (int i = 0; i < resultList.size(); i++) {
                if (resultList.get(i).getWord().getWordid().longValue() == wordid) {
                    if (Constants.UP_TYPE.equals(udtype)) {

                        if (i == 0) {
                            index = resultList.size() - 1;
                            break;

                        } else {
                            index = i - 1;
                            break;
                        }
                    } else {
                        if (i != resultList.size() - 1) {
                            index = i + 1;
                            break;
                        }

                    }

                }

            }
        }
        cu = resultList.get(index).getWord();
        cu.setSens(new ArrayList<String>());
        initWord(cu);
        req.setAttribute("libid", entity.getLibid());
        req.setAttribute("currentWord", cu);
        req.setAttribute("familiarity", entity.getFamiliarity());
        String lrtype = req.getParameter("lrtype");
        if (lrtype != null && !lrtype.isEmpty()) {
            //向左移动
            if (Constants.LEFT_TYPE.equals(lrtype)) {
                if (f == KnownLevel.Known.getValue()) {
                    entity.setFamiliarity(KnownLevel.Unknown.getValue());
                } else {
                    entity.setFamiliarity(entity.getFamiliarity() + 1);
                }
            } else if (Constants.RIGHT_TYPE.equals(lrtype)) {
                //向右边移动
                if (f == KnownLevel.Unknown.getValue()) {
                    entity.setFamiliarity(KnownLevel.Known.getValue());
                } else {
                    entity.setFamiliarity(entity.getFamiliarity() - 1);
                }

            }
            try {
                learningStatusService.changeStatus(entity);
            } catch (Exception e) {
                log.error("修改用户学习状态失败", e);

            }
        }
        this.forward(req, res, Constants.CURRENT_WORD_JSP);

    }

    public void initWord(SysLibWordsEntity word) {

        if (word.getSpelling() == null || word.getSpelling().isEmpty() || word.getWordid() == null) {
            return;
        }
        if (word.getSens() == null) {
            word.setSens(new ArrayList<String>());
        }
 
        String urlSens = HttpUtils.getResponse(Constants.DICT_CN_SEARCH_WORD + word.getSpelling().trim().toLowerCase());

              String p = HttpUtils.getResponse("http://r.5iwords.com/var/"+word.getSpelling().charAt(0)+"/"+word.getSpelling()+".txt","UTF-8");
           if(p!=null){
              word.setPartSpeechs(p.replaceAll("\n", "<br>"));
           }
        if (urlSens == null) {
            return;
        }
        String lines[] = urlSens.split("\n");
        for (int i = lines.length - 2; i >= 0; i--) {
            String line = lines[i];

            if (line.indexOf(Constants.DICT_CN_SEARCH_DEF) == -1 && line.indexOf(Constants.DICT_CN_SEARCH_DEF) == -1) {

                String s[] = line.split("<trans>");
                if (s.length == 2) {
                    s[0] = s[0].replaceAll("<sent>", "").replaceAll("</orig>", "").replaceAll("<orig>", "").replaceAll("&lt;em", "<span class=\"b\"").replaceAll("em&gt;", "span>").replaceAll("&gt;", ">").replaceAll("&lt;", "<");
                    s[1] = s[1].replaceAll("<trans>", "").replaceAll("</trans>", "").replaceAll("</sent>", "").replaceAll("&lt;em", "<span class=\"b\"").replaceAll("em&gt;", "span>").replaceAll("&gt;", ">").replaceAll("&lt;", "<");
                    word.getSens().add(s[0] + "#" + s[1]);

                }
            }

        }

    }

    public void doGetStatusList(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        LearningStatusEntity entity = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        try {
            entity.setFamiliarity(null);
            List<LearningStatusEntity> resultList = learningStatusService.getStatusList(entity);
            List<SysLibWordsEntity> wordList = wordService.findWordsBySysLibId(entity.getLibid());
            Map<Long, SysLibWordsEntity> map = new HashMap<Long, SysLibWordsEntity>();
            for (SysLibWordsEntity en : wordList) {
                map.put(en.getWordid(), en);
            }

            JSONArray defaultValue = new JSONArray();

            for (LearningStatusEntity en : resultList) {
                JSONObject value = new JSONObject();
                SysLibWordsEntity e = map.get(en.getWord().getWordid());
                value.put("id", en.getId());
                value.put("libid", en.getLibid());
                value.put("wordid", en.getWord().getWordid());
                if (e != null) {
                    value.put("spelling", CodeUtils.encode(e.getSpelling()));
                    value.put("meaning", CodeUtils.encode(e.getMeaning()));
                    value.put("phonetics", CodeUtils.encode(e.getPhonetics()));
                }
                value.put("userid", en.getUserid());
                value.put("familiarity", en.getFamiliarity());

                defaultValue.put(value);
            }
            result.put(Constants.DEFAULT_VALUE, defaultValue);

        } catch (Exception e) {
            log.error("获取用户学习状态列表失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
        }

    }

    public void doChangeStatus(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        LearningStatusEntity entity = initEntity(req);
        // type=0 左移动 type=1 右移动

        if ("0".equals(req.getParameter("type"))) {
            if (entity.getFamiliarity() == 7) {
                return;
            } else {
                entity.setFamiliarity(entity.getFamiliarity() + 1);
            }
        } else {
            if (entity.getFamiliarity() == 1) {
                entity.setFamiliarity(7);
            } else {
                entity.setFamiliarity(entity.getFamiliarity() - 1);
            }

        }
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);

        try {
            learningStatusService.changeStatus(entity);
        } catch (Exception e) {
            log.error("修改用户学习状态失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
        }

    }

    public void doMoveSysLib(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        LearningStatusEntity entity = initEntity(req);
        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        try {
            if (learningStatusService.moveSysLib(entity)) {
                result.put(Constants.DEFAULT_VALUE, true);
            }
        } catch (Exception e) {
            log.error("用户选择课本失败", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode(Constants.ERROR_CODE));
        }
    }

    public LearningStatusEntity initEntity(HttpServletRequest req) {
        LearningStatusEntity entity = new LearningStatusEntity();
        String userid = req.getParameter("userid");

        if (StringUtils.isNotBlank(userid)) {
            entity.setUserid(Long.parseLong(userid));
        } else {
            entity.setUserid(this.getUserId(req));
        }
        String wordid = req.getParameter("wordid");
        if (StringUtils.isNotBlank(wordid)) {
            SysLibWordsEntity word = new SysLibWordsEntity();
            word.setWordid(Long.parseLong(wordid));
            entity.setWord(word);
        }
        String libid = req.getParameter("libid");
        if (StringUtils.isNotBlank(libid)) {

            entity.setLibid(Long.parseLong(libid));
        }
        String familiarity = req.getParameter("familiarity");
        if (StringUtils.isNotBlank(familiarity)) {

            entity.setFamiliarity(Integer.parseInt(familiarity));
        } else {
            entity.setFamiliarity(0);

        }
        return entity;
    }
}
